package cn.chrilwe.pigpig.im.rule;

import java.util.ArrayList;
import java.util.List;

/**
  * 加权平滑轮询算法
 * @author chrilwe
 * 2020-9-5
 */
public class RoundRobinBalanceRule implements Rule {
	
	private static int staticWeightSum;
	
	private static List<ServiceDetail> list;
	
	public RoundRobinBalanceRule(List<ServiceDetail> list) {
		if(list == null || list.size() <= 0) {
			throw new RuntimeException("请先配置好需要负载均衡的服务器参数");
		}
		this.list = list;
		//求得静态配置的权重总值
		if(staticWeightSum <= 0) {
			for (ServiceDetail serviceDetail : list) {
				int staticWeight = serviceDetail.getStaticWeight();
				staticWeightSum += staticWeight;
			}
		}
	}

	@Override
	public ServiceDetail choose(String key) {
		//(dynamsicWeight = dynamsicWeight + staticWeight)
		for (ServiceDetail serviceDetail : list) {
			int dynamicsWeight = serviceDetail.getDynamicsWeight() + serviceDetail.getStaticWeight();
			serviceDetail.setDynamicsWeight(dynamicsWeight);
		}
		
		//求出最大dynamsicWeight值,和最大值所在的index
		int max = 0;
		int maxIndex = 0;
		for (int i=0; i<list.size(); i++) {
			int dynamicsWeight = list.get(i).getDynamicsWeight();
			if(dynamicsWeight > max) {
				max = dynamicsWeight;
				maxIndex = i;
			}
		}
		
		//将最大dynamsicWeight值减去静态配置的权重总值
		int n = max - staticWeightSum;
		list.get(maxIndex).setDynamicsWeight(n);
		return list.get(maxIndex);
	}
	
	public static void main(String[] args) {
		List<ServiceDetail> l = new ArrayList<ServiceDetail>();
		ServiceDetail e = new ServiceDetail();
		e.setHost("A");
		e.setStaticWeight(1);
		l.add(e);
		ServiceDetail e1 = new ServiceDetail();
		e1.setHost("B");
		e1.setStaticWeight(3);
		l.add(e1);
		ServiceDetail e2 = new ServiceDetail();
		e2.setHost("C");
		e2.setStaticWeight(5);
		l.add(e2);
		RoundRobinBalanceRule rule = new RoundRobinBalanceRule(l);
		for(int i=0;i<9;i++) {
			ServiceDetail choose = rule.choose("");
			System.out.println(choose.getHost());
		}
	}

}
